
package org.ssssssss.magicapi.mqtt;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.ssssssss.magicapi.Const;
import org.tio.core.ChannelContext;

import net.dreamlu.iot.mqtt.codec.MqttMessage;
import net.dreamlu.iot.mqtt.core.server.interceptor.IMqttMessageInterceptor;

/**
 * @author zcg
 * 2021年5月28日 下午9:32:38
 */

/**
 * mqtt 消息拦截器
 *
 */
public class MqttMessageInterceptor implements IMqttMessageInterceptor {
	private static final Logger logger = LoggerFactory.getLogger(MqttMessageInterceptor.class);

	@Override
	public void onAfterReceivedBytes(ChannelContext context, int receivedBytes) throws Exception {
		// 注意：此时 clientId 可能为空
//		String clientId = context.getBsId();
//		Node clientNode = context.getClientNode();
//		// ChannelStat channelStat = context.stat;
//		// 自定义规则，超限是可用 Tio.remove(context, "xxx超限"); 断开连接。
//		logger.info("===接收 client:{} clientId:{} data:{}b", clientNode, clientId, receivedBytes);
	}

	@Override
	public void onAfterDecoded(ChannelContext context, MqttMessage message, int packetSize) {
		// 注意：此时 clientId 可能为空
//		String clientId = context.getBsId();
//		Node clientNode = context.getClientNode();
//		logger.info("===解码 client:{} clientId:{} message:{}", clientNode, clientId, message);
	}

	@Override
	public void onAfterHandled(ChannelContext context, MqttMessage message, long cost) throws Exception {
		String method = "GET";
        Map<String, Object> params = new HashMap<>();	
        params.put("context",context);	
        params.put("message",message);	
        params.put("cost",cost);
        Const.getService().execute(method, Const.MQTT_MESSAGE_API, params);
		//String clientId = context.getBsId();
		//Node clientNode = context.getClientNode();
		//logger.info("===处理完成 ip:{} clientId:{} message:{} 耗时:{}", clientNode, clientId, message, cost);
		
//		MqttMessageType mmt = message.fixedHeader().messageType();
//		if(mmt!=MqttMessageType.PINGREQ&&mmt!=MqttMessageType.PINGRESP) {
//			String method = "GET";
//	        Map<String, Object> params = new HashMap<>();
//	        params.put("clientId",clientId);
//			if(mmt==MqttMessageType.PUBLISH) { //
//				Object payload = message.payload();				
//				params.put("topic",((MqttPublishVariableHeader)message.variableHeader()).topicName());
//		        //params.put("msg", new String(((ByteBuffer)payload).array()));// 转换成字符串
//				params.put("msg",payload);
//				Const.getService().execute(method, Const.MQTT_PUBLISH_API, params);			
//			}
//			else if(mmt==MqttMessageType.CONNECT) {
//		        params.put("msg", message.toString());
//				Const.getService().execute(method, Const.MQTT_CONNECT_API, params);				
//			}	
//			else if(mmt==MqttMessageType.DISCONNECT) {
//		        params.put("msg", message.toString());
//				Const.getService().execute(method, Const.MQTT_CONNECT_API, params);				
//			}			
//		}

	}
}
